package com.rom.ratethehell;

import java.util.ArrayList;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;

import com.rom.ratethehell.entities.Comment;
import com.rom.ratethehell.entities.ServerResponse;
import com.rom.ratethehell.protocol.tasks.SendCommentTask;
import com.rom.ratethehell.rate.custom_views.CommentView;
import com.rom.ratethehell.rate.custom_views.OnEnterListener;
import com.rom.ratethehell.rate.custom_views.WriteCommentView;

public class CommentsAdapter extends ArrayAdapter<Comment> {

	private WriteCommentView writeCommentView;

	public CommentsAdapter(final RateActivity context,final long id, final ArrayList<Comment> objects) {
		super(context,R.layout.view_comment, objects);
		writeCommentView = new WriteCommentView(context);
		writeCommentView.setOnEnterListener(new OnEnterListener() {
			
			@Override
			public void onEnter(String input) {
				final Comment c = new Comment(Global.userName,input);
				(new SendCommentTask(context,id, c) {
					
					@Override
					protected void onSuccess(ServerResponse result) {
						if (result.isOk()) {
						objects.add(c);
						notifyDataSetChanged();
						InputMethodManager inputManager = 
				        (InputMethodManager) context.
				            getSystemService(Context.INPUT_METHOD_SERVICE); 
				inputManager.hideSoftInputFromWindow(
						context.getCurrentFocus().getWindowToken(),
				        InputMethodManager.HIDE_NOT_ALWAYS);
						}
					}
				}).execute();
				
			}
		});

	}
	@Override
	public int getCount() {
		return super.getCount()+1;
	}
	@Override
	public Comment getItem(int i) {
		if (i==getCount()-1) return null;
		return super.getItem(i);
	}
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
//		if (convertView!=null) {
//			//TODO: fill this
//			//return convertView;
//		}
		return position==getCount()-1 ? writeCommentView : new CommentView(getContext(),getItem(position));
	}

}
